class Li_7_1_lock
{
    private int next;
    private int gap;
    private int sleepTime;

    Li_7_1_lock(int gap,int sleepTime)
    {
        this.next=0;
        this.gap=gap;
        this.sleepTime=sleepTime;
    }

    Integer getGap()
    {
        return this.gap;
    }

    synchronized public void waitThenPlus(int a)
    {
        while(this.next!=a)
            try
            {
                this.wait();
            }catch(InterruptedException ex){}
        this.next=(this.next+1)%this.gap;
        try
        {
            Thread.sleep(this.sleepTime);
        }catch(InterruptedException e){}
        this.notifyAll();
    }

    synchronized public void waitThenPrintThenPlus(int a,int i)
    {
        while(this.next!=a)
            try
            {
                this.wait();
            }catch(InterruptedException ex){}
        this.next=(this.next+1)%this.gap;
        try
        {
            Thread.sleep(this.sleepTime);
        }catch(InterruptedException e){}
        System.out.println("["+a+","+i+"],");
        this.notifyAll();
    }
}

public class Li_7_1 implements Runnable
{
    private Li_7_1_lock lock;
    private int start;
    private int end;

    public Li_7_1(int start,int end,Li_7_1_lock lock)
    {
        this.start=start;
        this.end=end;
        this.lock=lock;
    }

    public static void main(String args[])
    {
        Li_7_1_lock lock=new Li_7_1_lock(4,0);
        for(int i=0;i<lock.getGap();++i)
            new Thread(new Li_7_1(i,1000,lock),Integer.toString(i)).start();
    }

    synchronized public void run()
    {
        for(int i=this.start;i<this.end;i+=this.lock.getGap())
        {
//            synchronized(this.lock)
//            {
//                this.lock.waitThenPlus(this.start);
//                System.out.println("["+this.start+","+i+"],");
//            }
            this.lock.waitThenPrintThenPlus(this.start,i);

        }
        System.out.println(this.start+" 完啦！");
    }
}
